document.addEventListener('DOMContentLoaded', function () {
    const BASE_URL = '';

    // 1. 填充销售统计表格
    async function populateStatsTable() {
        const tableBody = document.querySelector('table tbody');
        if (!tableBody) return;
        
        try {
            const response = await fetch(`${BASE_URL}/api/sale_statistics_getall`);
            const data = await response.json();

            if (Array.isArray(data) && data.length > 0) {
                const rows = data.map(stat => `
                    <tr>
                        <td>${new Date(stat.date).toLocaleDateString()}</td>
                        <td>¥${(stat.price ?? 0).toFixed(2)}</td>
                        <td>${stat.amount ?? 0}</td>
                        <td>${stat.commodity_amount ?? 0}</td>
                        <td>¥${(stat.margin ?? 0).toFixed(2)}</td>
                    </tr>
                `).join('');
                tableBody.innerHTML = rows;
            } else {
                tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无统计数据</td></tr>';
            }
        } catch (error) {
            console.error('加载销售统计失败:', error);
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">加载数据失败</td></tr>';
        }
    }

    // 2. 渲染图表分析
    async function renderCharts() {
        const monthlyChartContainer = document.getElementById('monthlyTrendChart');
        const cashierChartContainer = document.getElementById('cashierRankChart');

        if (!monthlyChartContainer || !cashierChartContainer) {
            console.error('图表容器未找到!');
            return;
        }
        
        const monthlyChart = echarts.init(monthlyChartContainer);
        const cashierChart = echarts.init(cashierChartContainer);

        monthlyChart.showLoading();
        cashierChart.showLoading();

        try {
            // 获取月度趋势数据
            const statsResponse = await fetch(`${BASE_URL}/api/sale_statistics_getall`);
            const statsData = await statsResponse.json();
            
            // 获取收银员业绩数据
            const salesResponse = await fetch(`${BASE_URL}/api/sale_getall`);
            const salesData = await salesResponse.json();

            // --- A. 处理并渲染月度销售趋势图 ---
            if (Array.isArray(statsData)) {
                const monthlyData = statsData.reduce((acc, curr) => {
                    const month = new Date(curr.date).toISOString().slice(0, 7); // 格式 YYYY-MM
                    if (!acc[month]) {
                        acc[month] = { sales: 0, margin: 0 };
                    }
                    acc[month].sales += (curr.price ?? 0);
                    acc[month].margin += (curr.margin ?? 0);
                    return acc;
                }, {});

                const sortedMonths = Object.keys(monthlyData).sort();
                const monthlySales = sortedMonths.map(month => monthlyData[month].sales.toFixed(2));
                const monthlyMargins = sortedMonths.map(month => monthlyData[month].margin.toFixed(2));

                const monthlyOption = {
                    title: { text: '月度销售与毛利趋势' },
                    tooltip: { trigger: 'axis' },
                    legend: { data: ['总销售额', '总毛利'] },
                    xAxis: { type: 'category', data: sortedMonths },
                    yAxis: { type: 'value', axisLabel: { formatter: '¥{value}' } },
                    series: [
                        { name: '总销售额', type: 'line', data: monthlySales, smooth: true },
                        { name: '总毛利', type: 'line', data: monthlyMargins, smooth: true, lineStyle: { type: 'dashed' } }
                    ]
                };
                monthlyChart.setOption(monthlyOption);
            }
            monthlyChart.hideLoading();

            // --- B. 处理并渲染收银员业绩排行榜 ---
            if (Array.isArray(salesData)) {
                const cashierData = salesData.reduce((acc, curr) => {
                    const cashier = curr.cashier || '未知';
                    if (!acc[cashier]) {
                        acc[cashier] = 0;
                    }
                    acc[cashier] += (curr.total_price ?? 0);
                    return acc;
                }, {});

                const sortedCashiers = Object.entries(cashierData).sort((a, b) => a[1] - b[1]);

                const cashierOption = {
                    title: { text: '收银员业绩排行榜' },
                    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                    xAxis: { type: 'value', boundaryGap: [0, 0.01] },
                    yAxis: { type: 'category', data: sortedCashiers.map(c => c[0]) },
                    series: [{
                        name: '销售总额',
                        type: 'bar',
                        data: sortedCashiers.map(c => c[1].toFixed(2))
                    }]
                };
                cashierChart.setOption(cashierOption);
            }
            cashierChart.hideLoading();

        } catch (error) {
            console.error('渲染图表失败:', error);
            monthlyChart.hideLoading();
            cashierChart.hideLoading();
        }
    }

    // 初始化页面
    populateStatsTable();
    renderCharts();
}); 